package tul.cot.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;

public class Header implements WritableComparable<Header> {

	private Text label = new Text();
	private int seg;
	
	public Header() {} 
	
	public Header(String label, int seg) {
		set(label, seg);
	}
	
	public void set(String label, int seg) {
		this.label.set(label);
		this.seg = seg;
	}
	
	@Override
	public void readFields(DataInput in) throws IOException {
		label.readFields(in);
		seg = in.readInt();
	}

	@Override
	public void write(DataOutput out) throws IOException {
		label.write(out);
		out.writeInt(seg);
	}
	
	@Override
	public String toString() {
		return String.format("[%s; %d]", label.toString(), seg);
	}

	@Override
	public int compareTo(Header other) {
		
		if (this.seg < 0) {
			if (other.seg < 0) {
				return compare_seg_label(other);
			} else {
				return -1;
			}
		} else {
			if (other.seg < 0) {
				return 1;
			} else {
				return compare_label_seg(other);
			}
		}
	}
	
	private int compare_label_seg(Header other) {
		int cmpLabel = compareLabel(other);
		if (cmpLabel != 0)
			return cmpLabel;
		
		return compareSegment(other);
	}

	private int compare_seg_label(Header other) {
		int cmpSegment = compareSegment(other);
		if (cmpSegment != 0)
			return cmpSegment;
		
		return compareLabel(other);
	}

	public int compareSegment(Header other) {
		if (this.seg < other.seg)
			return -1;
		if (this.seg > other.seg)
			return 1;
		return 0;
	}
	
	public int compareLabel(Header other) {
		//TODO label vs getLabel()
		return this.getLabel().compareTo(other.getLabel());
	}
	
	
	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof Header))
			return false;
		
		Header other = (Header) obj;
		
		//TODO label vs getLabel()
		return (this.getLabel().equals(other.getLabel()) && this.seg == other.seg);
	}
	
	public String getLabel() {
		return label.toString();
	}
	
	public int getSegment() {
		return seg;
	}
	
	@Override
	public int hashCode() {
		//special hashCode for Histograms
		if (seg < 0)
			return -1;
		
		//TODO label vs getLabel()
		return getLabel().hashCode();
	}
	
}